package com.fjxd.city.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.fjxd.city.mapper.CityMapper;
import com.fjxd.city.pojo.City;
import com.fjxd.city.service.CityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author csw
 */
@Service
public class CityServiceImpl implements CityService {
    private final CityMapper cityMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    public CityServiceImpl(CityMapper cityMapper) {
        this.cityMapper = cityMapper;
    }

    @Override
    public List<City> getCityAll() {
        return cityMapper.getCityAll();
    }

    @Override
    public City getCityById(Integer id) {
        return cityMapper.getCityById(id);
    }

    @Override
    public Integer getCityIdByName(String cityName) {
        return cityMapper.getCityIdByName(cityName);
    }

    @Override
    public List<City> getCityIdListByName(String upCity, String downCity) {
        String key = "city:" + upCity + downCity;
        String jsonCity = redisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(jsonCity)) {
            return JSONUtil.toList(jsonCity, City.class);
        }
        List<City> value = cityMapper.getCityIdListByName(upCity, downCity);
        if (value.size() < 1) {
            return new ArrayList<>();
        }
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value));
        return cityMapper.getCityIdListByName(upCity, downCity);
    }


}
